<template>
<highlightjs language="JavaScript" highlightAuto top :code="code" />
</template>
<script>
export default {
  setup () {
    const code = `
    const state = reactive({
      map: ref(null),
      mapBox: ref(null),
      visible1: true,
      visible1Opacity: 100,
      visible2: true,
      visible2Opacity: 100,
      visible3: true,
      visible3Opacity: 100,
      formatTooltip: (val) => {
        return val / 100
      }
    })

    const init = () => {
      state.map = new Map({
        target: state.mapBox,
        layers: [
          new TileLayer({
            name: 'osm',
            source: new OSM()
          }),
          new LayerGroup({
            layers: [
              new Tile({
                name: 'tdroad',
                source: new XYZ({
                  url: 'http://t4.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=ab47b4591ab6e07e0530606eca973edd'
                })
              }),
              new Tile({
                name: 'tdtxt',
                source: new XYZ({
                  url: 'http://t3.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=ab47b4591ab6e07e0530606eca973edd'
                })
              })
            ]
          })
        ],
        view: new View({
          // 地图视图
          projection: 'EPSG:4326', // 坐标系，有EPSG:4326和EPSG:3857
          center: [116.41400, 39.91500], // 北京坐标
          zoom: 7 // 地图缩放级别（打开页面时默认级别）
        })
      })
    }

    // 显示/隐藏图层
    // setVisible可以设置图层显示或隐藏
    const changeCheckBox = (target, name) => {
      const layers = find(state.map, name)
      layers.setVisible(state[target])
    }

    // 查找图层
    const find = (source, name) => {
      const s = source.getLayers()
      for (let i = 0; i < s.getLength(); i++) { // 遍历所有图层
        if (s.item(i).get('name') === name) { // 根据图层名，查找并返回查找到的图层
          return s.item(i)
        }
        if (s.item(i) instanceof LayerGroup) { // 递归
          return find(s.item(i), name)
        }
      }
    }

    // 修改图层透明度
    // setOpacity可是设置图层的透明度，接收一个数值类型的参数
    const changeOpacity = (target, name) => {
      const layers = find(state.map, name)
      layers.setOpacity(parseFloat(state[target] / 100))
    }
    `
    return {
      code
    }
  }
}
</script>
